//
//  YXDownloadCompletedViewController.m
//  MockProject
//
//  Created by 周丽丽 on 16/8/24.
//  Copyright © 2016年 niuzhaowang. All rights reserved.
//

#import "YXDownloadCompletedViewController.h"
#import "YXDownloadCompletedTableViewCell.h"
#import "YXDownloadManger.h"
#import "YXDownloader.h"
@interface YXDownloadCompletedViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *deleteManagementButton;
@property (nonatomic, strong) UILabel *downloadCountLabel;
@property (nonatomic, strong) UILabel *noTaskLabel;
@property (nonatomic, strong) UIView *deleteView;
@property (nonatomic, strong) UIButton *chooseAllButton;
@property (nonatomic, strong) UIView *separatorLineView;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) YXDownloadManger *manger;
@property (nonatomic, strong) NSMutableArray *downloadersArr;
@property (nonatomic, strong) NSMutableArray<YXDownloadCompletedTableViewCell *> *deleteSelectedRowsArr;
@property (nonatomic, strong) NSMutableArray *deleteIndexPathArr;
@end

@implementation YXDownloadCompletedViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self setupDownloadCompletedTaskListTableView];
    [self setupManger];
    self.downloadersArr = self.manger.taskCompleteArr;
    self.deleteSelectedRowsArr = [NSMutableArray array];
    self.deleteIndexPathArr = [NSMutableArray array];
    [self setupNoTaskLabel];
    [self setupHeaderView];
    [self setupDeleteView];
    self.deleteView.hidden = YES;
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.downloadersArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *downloadCompletedTableViewCellID = @"downloadCompletedTableViewCellID";
    YXDownloadCompletedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:downloadCompletedTableViewCellID];
    if (!cell) {
        cell = [[YXDownloadCompletedTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:downloadCompletedTableViewCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.circleButton.selected = NO;
        cell.circleButton.hidden = YES;
    }
    cell.downloader = self.downloadersArr[indexPath.row];
    [self DownloadManagementMethod:cell];
    return cell;
}
#pragma mark - UITableViewDelegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    [self judgeWhetherHeaderViewISDisplayedAndSetDownloadCountLabel];
    return self.headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 48 * AutoSizeScaleX;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80 * AutoSizeScaleX;
}
- (void)DownloadManagementMethod:(YXDownloadCompletedTableViewCell *)cell{
    if (self.deleteManagementButton.selected) {
        cell.circleButton.hidden = NO;
        if (self.chooseAllButton.selected) {
            if(![self.deleteSelectedRowsArr containsObject:cell]) {
                cell.circleButton.selected = YES;
                cell.circleButton.backgroundColor = [UIColor redColor];
                [cell.circleButton setImage:[UIImage imageNamed:@"删除选择的对号图标"] forState:UIControlStateSelected];
                [self.deleteSelectedRowsArr addObject:cell];
                [self setupDeleteCount];
            }
        }else if (!self.chooseAllButton.selected) {
            [self.deleteSelectedRowsArr enumerateObjectsUsingBlock:^(YXDownloadCompletedTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.circleButton.selected = NO;
                obj.circleButton.backgroundColor = [UIColor whiteColor];
            }];
            [self.deleteSelectedRowsArr removeAllObjects];
            [self setupDeleteCount];
        }
        cell.circleButtonClickBlock = ^(YXDownloadCompletedTableViewCell *cell){
            if (![self.deleteSelectedRowsArr containsObject:cell]) {
                if (cell.circleButton.selected) {
                    [self.deleteSelectedRowsArr addObject:cell];
                    [self setupDeleteCount];
                }
            }else if ([self.deleteSelectedRowsArr containsObject:cell]) {
                if(!cell.circleButton.selected){
                    [self.deleteSelectedRowsArr removeObject:cell];
                    [self setupDeleteCount];
                }
            }
        };
    }else if (!self.deleteManagementButton.selected){
        cell.circleButton.hidden = YES;
        self.chooseAllButton.selected = NO;
        cell.circleButton.backgroundColor = [UIColor whiteColor];
        cell.circleButton.selected = NO;
    }
}
- (void)setupManger{
    self.manger = [YXDownloadManger sharedInstance];
    __weak typeof(self)weakSelf = self;
    self.manger.downloaderCompleteBlockForDownloadCompleteVC = ^{
        weakSelf.downloadersArr = weakSelf.manger.taskCompleteArr;
        [weakSelf.downloadCompletedTaskListTableView reloadData];
    };
}
- (void)setupDownloadCompletedTaskListTableView{
    UITableView *downloadCompletedTaskListTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:downloadCompletedTaskListTableView];
    downloadCompletedTaskListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    downloadCompletedTaskListTableView.delegate = self;
    downloadCompletedTaskListTableView.dataSource = self;
    self.downloadCompletedTaskListTableView = downloadCompletedTaskListTableView;
    [self.downloadCompletedTaskListTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(self.view);
    }];
}
- (void)setupDeleteView{
    UIView *deleteV = [[UIView alloc]init];
    deleteV.backgroundColor = [UIColor colorWithHexString:@"fcfcfc"];
    [self.view addSubview:deleteV];
    self.deleteView = deleteV;
    [self.deleteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(49);
    }];
    [self setupDeleteViewSubviews];
    [self layoutDeleteViewSubviews];
}
- (void)setupDeleteViewSubviews{
    UIButton *chooseAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chooseAllBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [chooseAllBtn setTitleColor:[UIColor colorWithHexString:@"403e3d"] forState:UIControlStateNormal];
    [chooseAllBtn setTitle:@"全选" forState:UIControlStateNormal];
    [self.deleteView addSubview:chooseAllBtn];
    [chooseAllBtn addTarget:self action:@selector(chooseAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.chooseAllButton = chooseAllBtn;
    
    UIView *separatorLineV = [[UIView alloc]init];
    separatorLineV.backgroundColor = [UIColor colorWithHexString:@"e2e4e4"];
    [self.deleteView addSubview:separatorLineV];
    self.separatorLineView = separatorLineV;
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    deleteBtn.userInteractionEnabled = NO;
    [deleteBtn setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
    [deleteBtn setTitle:[NSString stringWithFormat:@"删除(%zd)",self.deleteSelectedRowsArr.count] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.deleteView addSubview:deleteBtn];
    self.deleteButton = deleteBtn;
}
- (void)layoutDeleteViewSubviews{
    [self.chooseAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view.width * 0.5);
        make.left.top.height.equalTo(self.deleteView);
    }];
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.chooseAllButton.mas_right);
        make.centerY.equalTo(self.deleteView);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(20);
    }];
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.separatorLineView);
        make.right.top.height.equalTo(self.deleteView);
    }];
}
- (void)setupNoTaskLabel{
    UILabel *label = [[UILabel alloc]init];
    label.text = @"您还没有下载记录哦~";
    label.textColor = [UIColor colorWithHexString:@"ff7000"];
    [self.view addSubview:label];
    self.noTaskLabel = label;
    self.noTaskLabel.hidden = YES;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-50);
        make.centerX.equalTo(self.view);
    }];
}
- (void)judgeWhetherHeaderViewISDisplayedAndSetDownloadCountLabel{
    if (self.downloadersArr.count < 1) {
        self.headerView.alpha = 0;
        self.headerView.hidden = YES;
        self.noTaskLabel.hidden = NO;
    }else{
        self.headerView.alpha = 1;
        self.headerView.hidden = NO;
        self.noTaskLabel.hidden = YES;
    }
    self.downloadCountLabel.text = [NSString stringWithFormat:@"(下载完成(%zd)",self.downloadersArr.count];
}
- (void)setupHeaderView{
    UIView *headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 48)];
    headerV.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self.view addSubview:headerV];
    self.headerView = headerV;
    [self setupHeaderSubviews];
    [self layoutHeaderSubviews];
}
- (void)setupHeaderSubviews{
    UIButton *deleteManagementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteManagementBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    deleteManagementBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [deleteManagementBtn setTitleColor:[UIColor colorWithHexString:@"403e3d"] forState:UIControlStateNormal];
    [deleteManagementBtn setTitleColor:[UIColor colorWithHexString:@"ff4600"] forState:UIControlStateSelected];
    [deleteManagementBtn setTitle:@"删除管理" forState:UIControlStateNormal];
    [deleteManagementBtn setTitle:@"取消" forState:UIControlStateSelected];
    [deleteManagementBtn setImage:[UIImage imageNamed:@"删除管理按钮"] forState:UIControlStateNormal];
    [deleteManagementBtn setImage:[[UIImage alloc]init] forState:UIControlStateSelected];
    [deleteManagementBtn addTarget:self action:@selector(deleteManagementBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:deleteManagementBtn];
    self.deleteManagementButton = deleteManagementBtn;
    
    UILabel *downloadCountLbl = [[UILabel alloc]init];
    downloadCountLbl.textAlignment = NSTextAlignmentRight;
    downloadCountLbl.font = [UIFont systemFontOfSize:13];
    downloadCountLbl.textColor = [UIColor colorWithHexString:@"a5a2a1"];
    [self.headerView addSubview:downloadCountLbl];
    self.downloadCountLabel = downloadCountLbl;
}
- (void)layoutHeaderSubviews{
    [self.deleteManagementButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.headerView);
        make.left.equalTo(self.headerView).offset(15);
        make.right.equalTo(self.headerView.mas_centerX);
    }];
    [self.downloadCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.deleteManagementButton.mas_right);
        make.right.equalTo(self.headerView).offset(-15);
        make.centerY.equalTo(self.deleteManagementButton);
    }];
}
- (void)deleteManagementBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.deleteView.hidden = NO;
    }else if(!sender.selected){
        self.deleteView.hidden = YES;
        self.chooseAllButton.selected = NO;
    }
    [self.downloadCompletedTaskListTableView reloadData];
}
- (void)chooseAllBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    [self.downloadCompletedTaskListTableView reloadData];
}
- (void)deleteBtnClick:(UIButton *)sender{
    if (self.chooseAllButton.selected || self.deleteSelectedRowsArr.count == self.downloadersArr.count) {
        [self.manger removeAllCompleteDownloader];
        [self.deleteSelectedRowsArr removeAllObjects];
        [self.deleteIndexPathArr removeAllObjects];
        [self setupDeleteCount];
        self.deleteView.hidden = YES;
        self.chooseAllButton.selected = NO;
        self.deleteManagementButton.selected = NO;
        [self.downloadCompletedTaskListTableView reloadData];
    }else  if (self.deleteSelectedRowsArr.count < self.downloadersArr.count && !self.chooseAllButton.selected) {
        [self.deleteSelectedRowsArr enumerateObjectsUsingBlock:^(YXDownloadCompletedTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.deleteIndexPathArr addObject: [self.downloadCompletedTaskListTableView indexPathForCell:obj]];
        }];
        [self.deleteIndexPathArr enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.manger removeDownloader:self.manger.taskCompleteArr[obj.row]];
        }];
        self.deleteView.hidden = NO;
        [self.deleteIndexPathArr removeAllObjects];
        [self.downloadCompletedTaskListTableView reloadData];
    }
}
- (void)setupDeleteCount{
    if (self.deleteSelectedRowsArr.count == 0) {
        self.deleteButton.userInteractionEnabled = NO;
        [self.deleteButton setTitleColor:[UIColor colorWithHexString:@"cccccc"] forState:UIControlStateNormal];
    }else if (self.deleteSelectedRowsArr.count > 0) {
        self.deleteButton.userInteractionEnabled = YES;
        [self.deleteButton setTitleColor:[UIColor colorWithHexString:@"ff4600"] forState:UIControlStateNormal];
    }
    [self.deleteButton setTitle:[NSString stringWithFormat:@"删除(%zd)",self.deleteSelectedRowsArr.count] forState:UIControlStateNormal];
}
@end
